import { createRouter, createWebHistory } from 'vue-router';
import { ROUTE_HOME, ROUTE_LOGIN } from '@/utils/constants';
import { getToken } from '@/utils/auth';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import store from '@/store';

// 路由元信息
/**
 * 路由元信息
 * @param {string} title 标题
 * @param {string} icon 图标
 * @param {boolean} affix 是否固定标签
 * @param {boolean} noCache 是否缓存
 * @param {boolean} hidden 是否在菜单中隐藏
 * @param {Array} roles 可访问角色
 */

// 静态路由
export const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/Register.vue'),
    meta: { title: '注册', hidden: true }
  },
  {
    path: '/forgot-password',
    name: 'ForgotPassword',
    component: () => import('@/views/auth/ForgotPassword.vue'),
    meta: { title: '找回密码', hidden: true }
  },
  {
    path: '/404',
    name: 'Page404',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404', hidden: true }
  },
  {
    path: '/403',
    name: 'Page403',
    component: () => import('@/views/error/403.vue'),
    meta: { title: '403', hidden: true }
  },
  {
    path: '/500',
    name: 'Page500',
    component: () => import('@/views/error/500.vue'),
    meta: { title: '500', hidden: true }
  },
  {
    path: '/',
    component: () => import('@/views/layout/Layout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'dashboard', affix: true }
      }
    ]
  }
];

// 动态路由，根据权限动态加载
export const asyncRoutes = [
  {
    path: '/system',
    component: () => import('@/views/layout/Layout.vue'),
    redirect: '/system/user',
    meta: { title: '系统管理', icon: 'setting', roles: ['admin'] },
    children: [
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/system/user/index.vue'),
        meta: { title: '用户管理', icon: 'user', roles: ['admin'] }
      },
      {
        path: 'role',
        name: 'Role',
        component: () => import('@/views/system/role/index.vue'),
        meta: { title: '角色管理', icon: 'users', roles: ['admin'] }
      },
      {
        path: 'menu',
        name: 'Menu',
        component: () => import('@/views/system/menu/index.vue'),
        meta: { title: '菜单管理', icon: 'menu', roles: ['admin'] }
      }
    ]
  },
  {
    path: '/profile',
    component: () => import('@/views/layout/Layout.vue'),
    redirect: '/profile/index',
    meta: { hidden: true },
    children: [
      {
        path: 'index',
        name: 'Profile',
        component: () => import('@/views/profile/index.vue'),
        meta: { title: '个人中心', icon: 'user' }
      }
    ]
  },
  // 404页面必须放在最后
  { path: '/:pathMatch(.*)*', redirect: '/404', meta: { hidden: true } }
];

// 创建路由
const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes,
  scrollBehavior: () => ({ top: 0 })
});

// NProgress配置
NProgress.configure({ showSpinner: false });

// 白名单路由
const whiteList = ['/login', '/register', '/forgot-password', '/404', '/403', '/500'];

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start();
  
  // 设置标题
  document.title = to.meta.title ? `${to.meta.title} - ${import.meta.env.VITE_APP_TITLE}` : import.meta.env.VITE_APP_TITLE;
  
  // 判断是否有token
  const hasToken = getToken();
  
  if (hasToken) {
    if (to.path === ROUTE_LOGIN) {
      // 如果已登录，重定向到首页
      next({ path: ROUTE_HOME });
      NProgress.done();
    } else {
      // 判断用户信息是否存在
      const hasRoles = store.getters.roles && store.getters.roles.length > 0;
      
      if (hasRoles) {
        next();
      } else {
        try {
          // 获取用户信息
          const { roles } = await store.dispatch('user/getUserInfo');
          
          // 根据角色生成可访问路由
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles);
          
          // 动态添加路由
          accessRoutes.forEach(route => {
            router.addRoute(route);
          });
          
          // 确保路由完整性
          next({ ...to, replace: true });
        } catch (error) {
          // 出错时重置token并跳转到登录页
          await store.dispatch('user/resetToken');
          console.error(error);
          next(`${ROUTE_LOGIN}?redirect=${encodeURIComponent(to.path)}`);
          NProgress.done();
        }
      }
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      // 白名单路由直接访问
      next();
    } else {
      // 非白名单路由重定向到登录页
      next(`${ROUTE_LOGIN}?redirect=${encodeURIComponent(to.path)}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // 结束进度条
  NProgress.done();
});

export default router; 